package partner

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
)

type Logger struct {
	L  *zap.Logger
	lj *lumberjack.Logger
}

// NewLogger 得到实例
// filePath string        文件路径
// pod      bool          print only debug 仅Debug打印
// options  []zap.option  其它选项
func NewLogger(filePath string, pod bool, options ...zap.Option) *Logger {
	cfg := zap.NewProductionEncoderConfig()
	cfg.EncodeTime = zapcore.ISO8601TimeEncoder
	lumberjackLogger := &lumberjack.Logger{
		Filename:   filePath,
		MaxSize:    2,
		MaxAge:     100,
		MaxBackups: 10,
		LocalTime:  true,
		Compress:   false,
	}
	if len(options) == 0 {
		options = append(options, zap.AddCaller(), zap.AddCallerSkip(1))
	}
	l := zap.New(
		zapcore.NewTee(
			zapcore.NewCore(
				zapcore.NewJSONEncoder(cfg),
				zapcore.AddSync(lumberjackLogger),
				zap.LevelEnablerFunc(func(level zapcore.Level) bool {
					return level != zapcore.DebugLevel
				}),
			),
			zapcore.NewCore(
				zapcore.NewConsoleEncoder(cfg),
				zapcore.Lock(os.Stdout),
				zap.LevelEnablerFunc(func(level zapcore.Level) bool {
					return !pod || level == zapcore.DebugLevel
				}),
			),
		),
		options...,
	)
	return &Logger{
		L:  l,
		lj: lumberjackLogger,
	}
}

func (l *Logger) Close() {
	_ = l.lj.Close()
	_ = l.L.Sync()
}

func (l *Logger) Info(msg string, fields ...zap.Field) {
	l.L.Info(msg, fields...)
}

func (l *Logger) Debug(msg string, fields ...zap.Field) {
	if gin.Mode() == gin.ReleaseMode {
		return
	}
	l.L.Debug(msg, fields...)
}

func (l *Logger) Warn(msg string, fields ...zap.Field) {
	l.L.Warn(msg, fields...)
}

func (l *Logger) Error(msg string, fields ...zap.Field) {
	l.L.Error(msg, fields...)
}

func (l *Logger) DPanic(msg string, fields ...zap.Field) {
	l.L.DPanic(msg, fields...)
}

func (l *Logger) Panic(msg string, fields ...zap.Field) {
	l.L.Panic(msg, fields...)
}

func (l *Logger) Fatal(msg string, fields ...zap.Field) {
	l.L.Fatal(msg, fields...)
}
